package mapservice

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

type Location struct {
	Lat float64 `json:"lat"`
	Lng float64 `json:"lng"`
}

type GeocodingResponse struct {
	Status int `json:"status"`
	Result struct {
		Location Location `json:"location"`
	} `json:"result"`
}

type MapService struct {
	ak           string
	geocodingUrl string
}

func NewMapService(ak, geocodingUrl string) *MapService {
	return &MapService{
		ak:           ak,
		geocodingUrl: geocodingUrl,
	}
}

// GetLocationByAddress 根据地址获取经纬度
func (s *MapService) GetLocationByAddress(address string) (*Location, error) {
	// 构建请求URL
	params := url.Values{}
	params.Set("address", address)
	params.Set("output", "json")
	params.Set("ak", s.ak)

	reqUrl := fmt.Sprintf("%s?%s", s.geocodingUrl, params.Encode())

	// 发送HTTP请求
	resp, err := http.Get(reqUrl)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	// 解析JSON响应
	var geocodingResp GeocodingResponse
	err = json.Unmarshal(body, &geocodingResp)
	if err != nil {
		return nil, err
	}

	// 检查响应状态
	if geocodingResp.Status != 0 {
		return nil, errors.New("百度地图API请求失败")
	}

	return &geocodingResp.Result.Location, nil
}

// GetLocationByAddressWithCity 根据地址和城市获取经纬度（更精确）
func (s *MapService) GetLocationByAddressWithCity(address, city string) (*Location, error) {
	// 构建请求URL
	params := url.Values{}
	params.Set("address", address)
	params.Set("city", city)
	params.Set("output", "json")
	params.Set("ak", s.ak)

	reqUrl := fmt.Sprintf("%s?%s", s.geocodingUrl, params.Encode())

	// 发送HTTP请求
	resp, err := http.Get(reqUrl)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	// 解析JSON响应
	var geocodingResp GeocodingResponse
	err = json.Unmarshal(body, &geocodingResp)
	if err != nil {
		return nil, err
	}

	// 检查响应状态
	if geocodingResp.Status != 0 {
		return nil, errors.New("百度地图API请求失败")
	}

	return &geocodingResp.Result.Location, nil
}
